<template>
	<view>
		<!-- navbar -->
		<van-nav-bar @click-left="$back" left-arrow title="确认订单" :border="false" />
		<!-- scroll-view -->
		<scroll-view scroll-y :style="{height: height, backgroundColor: '#f8f8f8'}">
			<view style="padding: 32rpx;">
				<view class="orders-title">
					<view class="van-hairline--bottom" style="padding: 32rpx 0;">樱花屋</view>
				</view>
				<van-cell-group :border="false">
					<van-cell size="large" title="预留电话">
						<text style="font-size: 32rpx;color: #000000;" v-if="userInfo.phone">{{userInfo.phone}}</text>
						<van-button v-else type="danger" size="mini" open-type="getPhoneNumber" @getphonenumber="getPhone">手机号</van-button>
					</van-cell>
					<van-cell size="large" title="就餐时间" :border="false" v-if="orderType === '1'">
						<text style="font-size: 32rpx;color: #000000;">立即取单</text>
					</van-cell>
					<van-cell @click="chooseAddress" size="large" title="送货地址" is-link :border="false" v-if="orderType === '2'">
						<text v-if="address == undefined">请选择收货地址</text>
						<view class="van-ellipsis" style="font-size: 32rpx;color: #000000;" v-else>
							{{address}}
						</view>
					</van-cell>	
				</van-cell-group>
				<view style="height: 32rpx;" />
				<van-cell-group :border="false">
					<van-cell link-type="navigateTo" :url="`/pages/order/remark?remark=${remark}`" size="large" title="订单备注" is-link :border="false">
						<text v-if="remark == ''">口味、偏好等要求</text>
						<view class="van-ellipsis" style="font-size: 32rpx;color: #000000;" v-else>
							{{remark}}
						</view>
					</van-cell>	
				</van-cell-group>
				<view style="height: 32rpx;" />
				<view class="orders-title">
					<view class="van-hairline--bottom" style="padding: 32rpx 0;">共一份商品</view>
				</view>
				<van-cell-group :border="false">
					<van-cell size="large" center v-for="item in checkedGoodsList" :key="item.id">
						<view slot="title" style="display: flex;align-items: center;">
							<van-image radius="8rpx" width="64rpx" height="64rpx"
								:src="base_url + item.image" />
							<view class="orders-img-title">
								<text style="color: #000;font-size: 28rpx;line-height: 28rpx;">{{item.goodsName}}</text>
								<text style="color: #999999;font-size: 24rpx;">x{{item.count}}</text>
							</view>
						</view>
						<text style="color: #000000;">&yen;{{item.count * item.price}}</text>
					</van-cell>
					<van-cell link-type="navigateTo" :url="couponPriceStatus!=0 ? `/pages/order/chooseCoupon?status=${couponPriceStatus}&coupon=${coupon}&price=${totalPrice}` : null" size="large" title="优惠券" :is-link="couponPriceStatus!=0">
						<text v-if="couponPriceStatus == 0">无可用券</text>
						<view v-else-if="couponPriceStatus == 1" style="height: 100%;font-size: 24rpx;border-radius: 24rpx; padding: 0 16rpx;background-color: #EE0A24;color: #fff;">未选红包, 最高{{couponPriceHeighNum}}元可用</view>
						<text v-else-if="couponPriceStatus == 2" style="color: #EE0A24;font-size: 32rpx;">-&yen;{{couponPriceHeighNum}}</text>
					</van-cell>
					<van-cell size="large">
						<text style="font-size: 36rpx;color: #000000;">小计: ¥<text
								style="font-weight: bold;">{{totalPrice - (couponPriceStatus==2? couponPriceHeighNum : 0)}}</text></text>
					</van-cell>
				</van-cell-group>
				<view style="height: 32rpx;" />
				<view class="orders-title">
					<view class="van-hairline--bottom" style="padding: 32rpx 0;">支付方式</view>
				</view>
				<van-radio-group :border="false" :value="payWay" @change="onChange">
					<van-cell-group>
						<van-cell size="large" :icon="item.icon" :title="item.title" clickable :data-name="item.value"
							@click="onClick" v-for="(item, index) in payWayList" :key="index">
							<text style="padding-right: 8rpx;font-size: 24rpx;" v-if="item.value === '1' && isPay1">余额不足</text>
							<van-radio style="position: relative;top: 4rpx;" checked-color="#ee0a24" slot="right-icon" :name="item.value" />
						</van-cell>
					</van-cell-group>
				</van-radio-group>
			</view>
		</scroll-view>
		<van-submit-bar :price="payPrice*100" button-text="确认下单" @submit="onSubmit" />
	</view>
</template>

<script>
	import {mapState, mapActions, mapGetters} from 'vuex';
	import {getPhone} from '../../api/home/index.js';
	import {toPay} from '../../api/order/index.js';
	import {
		base_url
	} from '../../utils/request.js';
	export default {
		data() {
			return {
				payWay: '0', // 支付方式 微信0 余额1 
				payWayList: [{
						title: '微信支付',
						value: '0',
						icon: 'wechat-pay'
					},
					{
						title: '余额支付',
						value: '1',
						icon: 'gold-coin'
					},
					{
						title: '线下支付',
						value: '2',
						icon: 'card'
					}
				],
				base_url,
				remark: '', // 备注
				coupon: null, // 优惠券id
				couponPriceStatus: 0, // 红包状态 0 无券 1 有券 2 已选择券
				couponPriceHeighNum: 0, // 红包价格
				address: undefined,
			}
		},
		computed: {
			...mapGetters(['totalPrice']),
			...mapState(['userInfo', 'checkedGoodsList', 'store', 'couponList', 'orderType']),
			height() {
				return this.scrollviewHeilght - 96 + 'px'
			},
			payPrice() {
				return this.totalPrice - (this.couponPriceStatus==2? this.couponPriceHeighNum : 0)
			},
			isPay1() {
				return this.payPrice > this.userInfo.balance
			}
		},
		onShow() {
			uni.$on('handleRemark', res => {
				this.remark = res;
				uni.$off('handleRemark');
			})
			uni.$on('handleCoupon', res => {
				if(res.id === -1) {
					this.couponPriceStatus = 1;
				} else {
					this.couponPriceStatus = 2;
				}
				this.coupon = res.id;
				this.couponPriceHeighNum = res.reduction;
				uni.$off('handleCoupon');
			})
		},
		onLoad() {
			if(this.couponList.length == 0) {
				// str = '无优惠券可用';
				this.couponPriceStatus = 0;
			} else {
				let max = this.couponList[0].reduction;
				this.couponList.forEach(item => {
					if(item.reduction > max) {
						max = item.reduction;
					}
				})
				this.couponPriceStatus = 1;
				this.couponPriceHeighNum = max;
				// str = '未选红包, 最高'+ max +'元可用';
			}
		},
		methods: {
			...mapActions(['setUserInfo']),
			// 选择地址
			chooseAddress() {
				let that = this;
				uni.chooseAddress({
					success(e) {
						const {provinceName, cityName, countyName, detailInfo} = e;
						that.address = provinceName + cityName + countyName + detailInfo;
					}
				})
			},
			onChange({
				detail
			}) {
				this.payWay = detail;
			},
			onClick(event) {
				const {
					name
				} = event.currentTarget.dataset;
				if(name == '1') {
					// 余额支付可用
					if(!this.isPay1) {
						this.payWay = name;
					// 余额不足	
					} else {
						this.$slTip('余额不足');
					}
				} else {
					this.payWay = name;
				}
			},
			onSubmit() {
				const {phone} = this.userInfo;
				if(!phone) {
					this.$slTip('请填写手机号');
					return
				}
				if(this.orderType === '2' && !this.address) {
					this.$slTip('请填写收货地址');
					return
				}
				const {id: storeId} = this.store;
				let detailList = this.checkedGoodsList.reduce((prev, item) => {
					prev.push({goodsId: item.id, total: item.count});
					return prev
				}, [])
				let postObj = {
					// deskId: 0, // 桌子id
					// couponId: 0, // 优惠券id
					phone, // 电话号码
					orderType: this.orderType, // 1店食 2外卖
					payType: (Number(this.payWay) + 1) + '', // 1微信 2余额 3线下
					storeId, // 门店id
					detailList // 商品
				};
				if(this.coupon) {
					postObj.couponId = this.coupon;
				}
				if(this.remark) {
					postObj.remark = this.remark;
				}
				if(this.orderType === '2') {
					postObj.address = this.address;
				}
				let that = this;
				this.$slLoading('支付中...').then(() => {
					toPay(postObj).then(res => {
						const {
							timeStamp,
							nonceStr,
							paySign,
							packageValue
						} = res.data
						uni.requestPayment({
							//相关支付参数
							'timeStamp': timeStamp,
							'nonceStr': nonceStr,
							'package': packageValue,
							'signType': "MD5",
							'paySign': paySign,
							//小程序微信支付成功的回调通知
							'success': function(res) {
								that.$slTip("支付成功", "success").then(() => {
									uni.redirectTo({
										url: '/pages/me/myOrders'
									});
								})
							},
							//小程序支付失败的回调通知
							'fail': function(res) {
								that.$slTip("支付失败").then(() => {
									uni.redirectTo({
										url: '/pages/me/myOrders'
									});
								})
							}
						})
					}).finally(() => {
						uni.hideLoading();
					})
				})
			},
			getPhone({detail}) {
				const that = this;
				let {errMsg, encryptedData, iv} = detail;
				if(errMsg === 'getPhoneNumber:ok') {
					uni.login({
						provider: 'weixin',
						success(e) {
							let {
								code,
								errMsg: errMsg1
							} = e;
							if (errMsg1 = 'login:ok') {
								getPhone({code, encryptedData, iv}).then(res => {
									const {data: userInfo} = res;
									that.setUserInfo({userInfo});
								})
							}
						}
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.orders-title {
		background-color: #fff;
		padding: 0 32rpx;
		font-size: 36rpx;
		font-weight: bold;
		color: #000000;
	}

	.orders-img-title {
		height: 100%;
		display: flex;
		flex-direction: column;
		padding-left: 16rpx;
	}
</style>
